
#define SPDLOG_HEADER_ONLY
#define FMT_HEADER_ONLY
#include <spdlog/spdlog.h>
#include <spdlog/async.h>
#include <spdlog/sinks/stdout_color_sinks.h>
#include "spdlog/sinks/rotating_file_sink.h"

#if !defined(_DEBUG) && !defined(NGITVERSION)
#include "ver_git.h"
#endif

#include "lua_log.hpp"

#define DEFAULT_PATTERN "%Y-%m-%d %H:%M:%S.%e [%^%6l%$] [t-%t]: %v"

std::vector<spdlog::sink_ptr> sinks;

auto console_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();

Log::Log()
{
    level_   = SPDLOG_LEVEL_DEBUG;
    pattern_ = DEFAULT_PATTERN;
}

void Log::info(const char* s)
{
    spdlog::info(s);
}

void Log::debug(const char* s)
{
    spdlog::debug(s);
}

void Log::error(const char* s)
{
    spdlog::error(s);
}

void Log::warn(const char* s)
{
    spdlog::warn(s);
}

void Log::set_file(const char* logger_name, int max_files, long long max_file_size)
{
    sinks.clear();
    sinks.push_back(console_sink);

    if (max_files <= 0)
        max_files = 2;
    if (max_file_size <= 0)
        max_file_size = 5 * 1024 * 1024;

    auto file_sink = std::make_shared<spdlog::sinks::rotating_file_sink_mt>(logger_name, max_file_size, max_files);
    sinks.push_back(file_sink);

    spdlog::set_default_logger(std::make_shared<spdlog::logger>("multi-sink", begin(sinks), end(sinks)));
}

void Log::set_pattern(const char* pattern)
{
    pattern_ = pattern;
    spdlog::set_pattern(pattern_);
}

void Log::set_level(int logger_level)
{
    spdlog::set_level(spdlog::level::level_enum(logger_level));
}

const char* Log::get_version()
{
#if !defined(GIT_VERSION)
    return "";
#else
    return "build: " __TIME__ " " __DATE__ " version: " GIT_VERSION;
#endif
}

void log_init()
{
    sinks.push_back(console_sink);
    spdlog::set_default_logger(std::make_shared<spdlog::logger>("multi-sink", begin(sinks), end(sinks)));

    spdlog::set_level(spdlog::level::debug);   // Set global log level to info
    spdlog::set_pattern(DEFAULT_PATTERN);
}

Log* newLog()
{
    auto p = new Log;
    return p;
}
